/***MsgDom By GYLite 2022-12-26
 * web客户端通讯类，提供与web客户端通讯的接口
*/
class MsgDom extends MsgBase{
	private static _instance:MsgDom;	
	public static getInstance():MsgDom
	{
		if(MsgDom._instance == null)
			MsgDom._instance = new MsgDom;
		return MsgDom._instance;
	}	
	public constructor() {
		super();
		let s= this;		
		window.addEventListener("message", s.onRecvMsg.bind(s), false);			
	}

	public sendAppletMsg(action:string, data:any = null, logLevel:number = Log.VERBOSE):void
	{
		if(window.parent == window)
		{
			Log.writeLog("MSG_" + MultiLang.str22,Log.WARN);
			return;
        }
        super.sendMsg(action, data, logLevel);	
		var obj:any = {};
		obj.action = action;
		obj.data = data;		
		var jsonStr:string = JSON.stringify(obj);
        if(logLevel > 0)
            Log.writeLog("MSG_" + MultiLang.str12 + jsonStr, logLevel);
		window.parent.postMessage(jsonStr, "*");
	}	

    public sendMsg(protocol:string, data:Object = null, logLevel:number = Log.VERBOSE):void
	{
		if(window.parent == window)
		{
			Log.writeLog("MSG_" + MultiLang.str22,Log.WARN);
			return;
        }
        super.sendMsg(protocol, data, logLevel);	
		var obj:any = {};
		obj.protocol = protocol;
		obj.data = data;		
		var jsonStr:string = JSON.stringify(obj);
        if(logLevel > 0)
            Log.writeLog("MSG_" + MultiLang.str12 + jsonStr, logLevel);
		window.parent.postMessage(jsonStr, "*");
	}

	protected onRecvMsg(event:any):void
	{
		var origin = event.origin;
		// if(origin == null && event.originalEvent &&  event.originalEvent.origin)
		// 	origin = event.originalEvent.origin;
		// if(origin == document.location.origin)return;		
		let objData:any = event.data;
        let logLevel:number;
        let s =this;
        logLevel = s._protocolDict[objData.protocol]?s._protocolDict[objData.protocol].logLevel:0;
		if(GYLite.CommonUtil.GYIs(objData, String))
		{
            Log.writeLog("MSG_" + MultiLang.str13 + objData, Log.VERBOSE);
            if(logLevel > 0)
                Log.writeLog("MSG_" + MultiLang.str13 + objData, logLevel);
			objData = JSON.parse(objData);
		}
        else if(logLevel > 0)
            Log.writeLog("MSG_" + MultiLang.str13 + JSON.stringify(objData), logLevel);
		super.recvMsg(objData);		
	}
	
}